package com.lwq.fast.log.fastlogserver.rabbitmq.listener;

import com.lwq.fast.log.fastlogserver.es.service.ElasticSearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 消息监听器，监听rabbitmq消息
 * @author 刘文强
 */
@Slf4j
public class RabbitConsumerListener implements ChannelAwareMessageListener {

    @Autowired
    private ElasticSearchService elasticSearchService;

    /**
     * 消费者名称
     */
    private String consumerName;

    public String getConsumerName() {
        return consumerName;
    }

    public void setConsumerName(String consumerName) {
        this.consumerName = consumerName;
    }

    public RabbitConsumerListener() {
    }

    public RabbitConsumerListener(String consumerName) {
        this.consumerName = consumerName;
    }

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String logMessage = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("deliveryTag=" + deliveryTag + " body=" + logMessage);
        try{
            elasticSearchService.logMessage2Es(logMessage);
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            log.error("RabbitConsumerListener onMessage error", e);
        }


    }
}
